

import Foundation
import UIKit
import CoreTelephony

import SystemConfiguration.CaptiveNetwork
import SystemConfiguration

import AppTrackingTransparency
import AdSupport


@objcMembers class FYPlatformUtil: NSObject {
        
    class func fy_getSystemLanguage() -> String {
        let languageValue = Locale.preferredLanguages.first
        if languageValue == nil || languageValue!.isEmpty {
            return ""
        }
        return languageValue!.split(separator: "-").first.map { String($0) } ?? ""
    }
    
    class func fy_getChargingStatus() -> Bool {
        let device = UIDevice.current
        device.isBatteryMonitoringEnabled = true
        
        if device.batteryState == .charging || device.batteryState == .full {
            return true
        } else {
            return false
        }
    }
    
    class func fy_getTimeZone() -> String {
        let timeZone = TimeZone.current.identifier
        return timeZone
    }
    
    class func fy_getMobileDevicePlatform() -> String {
        var newDeviceType = "unknown"
        let detailDeviceType = FYModelTypeUtil.fy_getMobileDeviceModelType()
        if detailDeviceType.hasPrefix("iPhone") {
            newDeviceType = "Mobile"
        } else if detailDeviceType.hasPrefix("iMac") || detailDeviceType.hasPrefix("Mac") {
            newDeviceType = "pc"
        } else if detailDeviceType.hasPrefix("iPad") {
            newDeviceType = "Tablet"
        }
        return newDeviceType
    }
    
    class func fy_getBatteryLevel() -> Float {
        let device = UIDevice.current
        device.isBatteryMonitoringEnabled = true
        
        let batteryCharge = device.batteryLevel
        var batteryLevel: Float = 0.0
        
        if batteryCharge > 0.0 {
            batteryLevel = batteryCharge * 100
        } else {
            return -1
        }
        
        return batteryLevel
    }
    
    
    
    class func fy_getCellularType() -> String {
        let info = CTTelephonyNetworkInfo()
        
        guard let radioDic = info.serviceCurrentRadioAccessTechnology, !radioDic.isEmpty else {
            return "notReachable"
        }
        
        let currentRadioAccessTechnology = radioDic.values.first!
        
        if #available(iOS 14.1, *) {
            if currentRadioAccessTechnology == CTRadioAccessTechnologyNRNSA || currentRadioAccessTechnology == CTRadioAccessTechnologyNR {
                return "5G"
            }
        }
        
        switch currentRadioAccessTechnology {
        
        case CTRadioAccessTechnologyLTE:
            return "4G"
        case CTRadioAccessTechnologyEdge, CTRadioAccessTechnologyGPRS, CTRadioAccessTechnologyCDMA1x:
            return "2G"
        case CTRadioAccessTechnologyWCDMA, CTRadioAccessTechnologyHSDPA, CTRadioAccessTechnologyHSUPA, CTRadioAccessTechnologyCDMAEVDORev0, CTRadioAccessTechnologyCDMAEVDORevA, CTRadioAccessTechnologyCDMAEVDORevB, CTRadioAccessTechnologyeHRPD:
            return "3G"
        
        default:
            return "Unknown"
        }
    }
    
    
    class func fy_isSimulatorCheckStatus() -> Bool {
        var systemInfo = utsname()
        uname(&systemInfo)
        let deviceType = withUnsafePointer(to: &systemInfo.machine) {
            $0.withMemoryRebound(to: CChar.self, capacity: 1) {
                String(cString: $0)
            }
        }
        return deviceType == "i386" || deviceType == "x86_64" || deviceType == "arm64"
    }
    
    class func fy_getNetworkType() -> String {

        var zeroAddress = sockaddr_storage()
        zeroAddress.ss_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.ss_family = sa_family_t(AF_INET)
        
        let sockaddrPtr = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { $0 }
        }
        
        guard let defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(nil, sockaddrPtr) else {
            return "notReachable"
        }
        
        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return "notReachable"
        }
        
        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)
        
        if !isReachable || needsConnection {
            return "notReachable"
        }
        
        if flags.contains(.isWWAN) {
            return FYPlatformUtil.fy_getCellularType()
        } else {
            return "WiFi"
        }
    }
    
//    class func fy_getIdfaAuthorizationStatusCallback(_ acceptBlock: (() -> Void)?) {
//        var utilCounter = 0
//        
//        let utilTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
//            if utilCounter == 10 {
//                acceptBlock?()
//                timer.invalidate()
//            } else {
//                utilCounter += 1
//            }
//        }
//        
//        if #available(iOS 14.0, *) {
//            ATTrackingManager.requestTrackingAuthorization { status in
//                if utilCounter < 10 {
//                    utilTimer.invalidate()
//                }
//                
//                acceptBlock?()
//                
//                switch status {
//                case .authorized:
//                    Trio_TargetTool.target_userBehaviorMethod("monitor-17")
//                default:
//                    Trio_TargetTool.target_userBehaviorMethod("monitor-18")
//                }
//            }
//        } else {
//            utilTimer.invalidate()
//            acceptBlock?()
//        }
//    }
    
    class func fy_getProxyStatus() -> Bool {
        guard let proxySettings = CFNetworkCopySystemProxySettings()?.takeRetainedValue() as? [String: Any] else {
            return false
        }
        
        let url = URL(string: "https://www.baidu.com")!
        guard let proxies = CFNetworkCopyProxiesForURL(url as CFURL, proxySettings as CFDictionary).takeRetainedValue() as? [[String: Any]] else {
            return false
        }
        
        guard let settings = proxies.first else {
            return false
        }
        
        if let proxyType = settings[kCFProxyTypeKey as String] as? String, proxyType == "kCFProxyTypeNone" {
            return false
        } else {
            return true
        }
    }
    
    class func fy_getNetworkTypeConvertToValue() -> String {
        let networkType = FYPlatformUtil.fy_getNetworkType()
        
        if networkType == "WiFi" {
            return "1"
        } else if networkType == "3G" {
            return "3"
        } else if networkType == "2G" {
            return "2"
        } else if networkType == "5G" {
            return "5"
        } else if networkType == "4G" {
            return "4"
        } else {
            return "0"
        }
    }
        
    class func fy_getScreenResolutionValue() -> String {
        let scaleScreen = UIScreen.main.scale
        let w = UIScreen.main.bounds.width * scaleScreen
        let h = UIScreen.main.bounds.height * scaleScreen
        return "\(Int(w))-\(Int(h))"
    }
    
    class func fy_getScreenBrightnessValue() -> Float {
        let brightness = UIScreen.main.brightness
        if brightness < 0.0 || brightness > 1.0 {
            return -1
        }
        return Float(brightness * 100)
    }
    
    
    
    class func fy_getJailBreakedStatus() -> Bool {
        if FYPlatformUtil.fy_isSimulatorCheckStatus() {
            return false
        }
        
        if UIApplication.shared.canOpenURL(URL(string: "cydia://")!) {
            print("isJailBreak2: The device is jail broken!")
            return true
        }
        
        if FileManager.default.fileExists(atPath: "/User/Applications/") {
            print("isJailBreak1: The device is jail broken!")
            return true
        }
        
        let jailbreakToolPaths = ["/Applications/Cydia.app", "/Library/MobileSubstrate/MobileSubstrate.dylib", "/bin/bash", "/usr/sbin/sshd", "/etc/apt"]
        for path in jailbreakToolPaths {
            if FileManager.default.fileExists(atPath: path) {
                return true
            }
        }
        
        return false
    }
    
    //import SystemConfiguration.CaptiveNetwork
    class func fy_getWifiInfo() -> [String: String]? {
        guard let interfaces = CNCopySupportedInterfaces() as? [String] else {
            return nil
        }
        
        for interfaceName in interfaces {
            guard let info = CNCopyCurrentNetworkInfo(interfaceName as CFString) as? [String: Any] else {
                continue
            }
            if let ssid = info["SSID"] as? String, let bssid = info["BSSID"] as? String {
                return ["ssid": ssid, "bssid": bssid]
            }
        }
        return nil
    }
}

